package com.jl.encrypt;

import cn.hutool.json.JSONUtil;
import com.jl.encrypt.annotate.Encode;
import com.jl.encrypt.config.SecretKeyConfig;
import com.jl.encrypt.util.AESUtils;
import com.jl.encrypt.util.RSAUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * json返参拦截
 */
@Slf4j
@ControllerAdvice
@ConditionalOnExpression("${security.encrypt.open:false}")
public class JResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private SecretKeyConfig secretKeyConfig;

    private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal<>();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getMethod().isAnnotationPresent(Encode.class) && secretKeyConfig.getOpen() ? true : false;
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Boolean status = encryptLocal.get();
        if (null != status && !status) {
            encryptLocal.remove();
            return body;
        }
        if (returnType.getMethod().isAnnotationPresent(Encode.class)) {
            String iv = AESUtils.generateRandomString(16);
            response.getHeaders().add("iv", iv);
            String content = JSONUtil.toJsonStr(body);
            String result = secretKeyConfig.getAes() == null ? RSAUtils.privateEncode(content, secretKeyConfig.getRsa().getPrivateKey()) : AESUtils.encode(content, secretKeyConfig.getAes().getKey(), iv);
            if (secretKeyConfig.getShowLog()) {
                log.info("原文参数：{}，加密后参数：{}", content, result);
            }
            return result;
        }
        return body;
    }
}
